﻿using Microsoft.EntityFrameworkCore;
using Mozhi.Abp.Module.DataLinkage.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace Mozhi.Abp.Module.DataLinkage.Repositories
{
    public class DataLinkageRepository : EfCoreRepository<DataLinkageDbContext, DataLinkage, Guid>, IDataLinkageRepository
    {
        public DataLinkageRepository(IDbContextProvider<DataLinkageDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<int> GetCountAsync(string keyword , Guid? providerId, Guid? consumerId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var count = await dbContext.Set<DataLinkage>().AsNoTracking()
                .WhereIf(providerId.HasValue , x=>x.ProviderId == providerId)
                .WhereIf(consumerId.HasValue,x=>x.ConsumerId== consumerId)
                .WhereIf(!keyword.IsNullOrEmpty(), x => x.ProviderContent.Contains(keyword) || x.ConsumerContent.Contains(keyword))
                .CountAsync(cancellationToken);

            return count;
        }

        public async Task<List<DataLinkage>> GetListAsync(string keyword, Guid? providerId, Guid? consumerId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var dataLinkages = await dbContext.Set<DataLinkage>().AsNoTracking()
                .WhereIf(providerId.HasValue, x => x.ProviderId == providerId)
                .WhereIf(consumerId.HasValue, x => x.ConsumerId == consumerId)
                .WhereIf(!keyword.IsNullOrEmpty(), x => x.ProviderContent.Contains(keyword) || x.ConsumerContent.Contains(keyword))
                .ToListAsync(cancellationToken);

            return dataLinkages;
        }

        public async Task<List<DataLinkage>> GetPagedListAsync(string keyword, Guid? providerId, Guid? consumerId, int skipCount, int maxResultCount, string sorting, bool includeDetails = false, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var dataLinkages = await dbContext.Set<DataLinkage>().AsNoTracking()
               .WhereIf(providerId.HasValue, x => x.ProviderId == providerId)
               .WhereIf(consumerId.HasValue, x => x.ConsumerId == consumerId)
               .WhereIf(!keyword.IsNullOrEmpty(), x => x.ProviderContent.Contains(keyword) || x.ConsumerContent.Contains(keyword))
                .OrderByIf<DataLinkage, IQueryable<DataLinkage>>(!sorting.IsNullOrWhiteSpace(), sorting)
                .PageBy(skipCount, maxResultCount).ToListAsync(GetCancellationToken(cancellationToken));

            return dataLinkages;
        }
    }
}
